package com.bjy.qa.agent.tools.resttemplate;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;

/**
 * 日志拦截器（restTemplate 的 HttpRequest 拦截器）
 */
public class LoggerRequestInterceptor implements ClientHttpRequestInterceptor {
    private static final Logger logger = LoggerFactory.getLogger(LoggerRequestInterceptor.class);

    @Override
    public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
        loggerRequest(request, body);
        ClientHttpResponse response = execution.execute(request, body);
        loggerResponse(response);
        return response;
    }

    /**
     * 请求日志
     * @param request request
     * @param body body
     * @throws IOException
     */
    private void loggerRequest(HttpRequest request, byte[] body) throws IOException {
        logger.info("<-- {}: {}", request.getMethod(), request.getURI());
        logger.info("<-- headers: {}", request.getHeaders());
        logger.info("<-- body: {}", new String(body, StandardCharsets.UTF_8));
    }

    /**
     * 响应日志
     * @param response response
     * @throws IOException
     */
    private void loggerResponse(ClientHttpResponse response) throws IOException {
        StringBuilder sb = new StringBuilder();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(response.getBody(), "UTF-8"));
        String line = bufferedReader.readLine();
        while (line != null) {
            sb.append(line);
            sb.append('\n');
            line = bufferedReader.readLine();
        }
        logger.info("--> {}", response.getStatusCode());
        logger.info("--> headers: {}", response.getHeaders());
        logger.info("--> body: {}", sb.toString());
    }
}
